<script setup lang="ts">
import { request } from '@/apis';
import { Loading, closeToast, showLoadingToast, showToast, type ActionSheetAction } from 'vant';
import { onMounted, ref } from 'vue';
import base64ToBlob from 'b64-to-blob'

// 5.获取用户信息数据
const profile = ref<ProfileInfo>({} as ProfileInfo)
onMounted(async () => {
  showLoadingToast({ message: '正在加载...', duration: 0, forbidClick: true })
  const res = await request.get<MkResponse<ProfileInfo>>('member/profile')
    // 关闭弹窗
    closeToast() 
  profile.value = res.data.result
    console.log(profile.value);
  // 处理日期---使用-进行封割
    birthday.value = profile.value.birthday.split('-')
})

// 1.头像处理部分
const showAvatar = ref(false)
const actionAvatar = [
  { name: '相册' },
  { name: '拍照' }
]
const onSelectAvatar = async (action: ActionSheetAction, index: number) => {
  // console.log(action,index);
  // 隐藏动作面板
  showAvatar.value = false
if (index===0) {
  // console.log('去相册');
  const data = await mk.pickerPhoto()
  onUpdateAvatar(data)
} else if (index===1) {
  // console.log('去拍照');
  onUpdateAvatar(await mk.pickerCamera()) 
}
}

const onUpdateAvatar = async (str:string) => {
  // 1. 把base64编码转成图片文件对象
  const image = base64ToBlob(str, 'image/jpeg')
  console.log(image);

  // 2.包装formData对象
  const fd = new FormData()
  fd.append('file', image, Date.now() + '.jpeg')

  // 3.调用接口
  showLoadingToast({ message: '正在加载...', duration: 0, forbidClick: true })
  const res = await request.post<MkResponse<{ avatar: string }>>('member/profile/avatar', fd)
  closeToast()
  // console.log(res);
  profile.value.avatar = res.data.result.avatar

  // 4.更新原生侧头像
  const user = await mk.queryUser()
  user.avatar = res.data.result.avatar
  await mk.updateUser(user)
  showToast({message:'更新成功'})
  
}

// 2.选择出生日期
const showBirthdayPopup = ref(false)
const currentDate = new Date()
const birthday = ref([
  String(currentDate.getFullYear()),
  String(currentDate.getMonth() + 1),
  String(currentDate.getDay()),
])
const selectBirthDay = (data:{selectedValues:string[]}) => {
  // console.log(data.selectedValues);
  showBirthdayPopup.value = false
  birthday.value = data.selectedValues
  profile.value.birthday = data.selectedValues.join('-')
}

// 3.选择地址
const showLocationPopup = ref(false)
const areaColumns = ref<AreaColumns>({} as AreaColumns)
onMounted(async () => {
try {
  areaColumns.value = await mk.getAreaColumns()
} catch (error) {
  showToast('美寇SDK异常')
}
})
const onSelectLocation = (data:{selectedValues:string[]}) => {
  showLocationPopup.value = false
  // 处理数据
  profile.value.provinceCode = Number(data.selectedValues[0])
  profile.value.cityCode = Number(data.selectedValues[1])
  profile.value.countyCode = Number(data.selectedValues[2])

  const provinceName = areaColumns.value.province_list[Number(data.selectedValues[0])]
  const cityName = areaColumns.value.city_list[Number(data.selectedValues[1])]
  const countyName = areaColumns.value.county_list[Number(data.selectedValues[2])]
  // console.log(provinceName,cityName,countyName);

  profile.value.fullLocation = `${provinceName} ${cityName} ${countyName}`
  
}

// 4. 选择职业
const columns = [
  { text: '软件工程师', value: '软件工程师' },
  { text: '医生', value: '医生' },
  { text: '教师', value: '教师' },
  { text: '律师', value: '律师' },
  { text: '会计师', value: '会计师' },
  { text: '销售经理', value: '销售经理' },
  { text: '市场营销专员', value: '市场营销专员' },
  { text: '建筑师', value: '建筑师' },
  { text: '护士', value: '护士' },
  { text: '机械工程师', value: '机械工程师' }
]
const showProfessionPopup = ref(false)
const onSelecProfession = (data: { selectedValues: string[] }) => {
  console.log(data.selectedValues);
  showProfessionPopup.value = false

  profile.value.profession = data.selectedValues[0]
}

// 6.保存
const loading = ref(false)
const onSubmit = async () => {
  console.log(profile.value);
  loading.value = true
  mk.vibrator()
  await request.put('member/profile', profile.value)
  loading.value = false

  // 4.更新原生侧昵称
  const user = await mk.queryUser()
  user.nickname = profile.value.nickname
  await mk.updateUser(user)
  showToast({message:'更新成功'})
}
</script>

<template>
  <div class="profile-edit-page">
  <!-- 头像部分 -->
  <!--  round --- :round = 'true' -->
  <div class="avatar">
  <van-image round width="100" height="100" class="avatar-img" :src="profile.avatar" >
  </van-image>
  <!-- 修改头像 -->
  <div class="avatar-btn"  @click="showAvatar = true">
     <span> 修改头像 </span>
  </div>
   <!-- 头像动作面板 -->
   <van-action-sheet v-model:show="showAvatar" :actions="actionAvatar" @select="onSelectAvatar" cancel-text="取消" style="padding-bottom: 30px;"/>
  </div>
  <!-- 中间表单部分 -->
  <van-cell-group>
    <van-field v-model="profile.account" label="账号" readonly />
    <van-field v-model="profile.nickname" label="昵称" placeholder="请输入昵称"/>
    <van-cell  title="性别" class="gender">
      <van-radio-group  direction="horizontal" v-model="profile.gender">
      <van-radio name="男">男</van-radio>
      <van-radio name="女">女</van-radio>
      <van-radio name="未知">未知</van-radio>
    </van-radio-group>
    </van-cell>
      <van-field v-model="profile.birthday" label="生日" placeholder="请选择日期" readonly @click="showBirthdayPopup = true"/>
      <!-- 选择生日弹窗 -->
      <van-popup v-model:show="showBirthdayPopup" position="bottom">
        <van-date-picker v-model="birthday" title="选择日期" :min-date="new Date(1960,0,1)" @cancel='showBirthdayPopup = false' @confirm="selectBirthDay"/>
      </van-popup>
      <van-field v-model="profile.fullLocation" label="所在地" placeholder="请选择所在地" readonly @click="showLocationPopup=true"/>
      <!-- 选择所在地弹窗 -->
      <van-popup v-model:show="showLocationPopup" position="bottom">
        <van-area title="选择所在地" :area-list="areaColumns" @cancel="showLocationPopup=false" @confirm="onSelectLocation"/>
      </van-popup>
      <van-field v-model="profile.profession" label="职业" placeholder="请选择职业" readonly @click="showProfessionPopup = true"/>
      <!-- 选择职业弹窗 -->
      <van-popup v-model:show="showProfessionPopup" position="bottom">
        <van-area title="标题" :columns="columns" @cancel="showProfessionPopup=false" @confirm="onSelecProfession"/>
      </van-popup>
</van-cell-group>
<!-- 按钮区域 -->
<!-- block:独占一行 -->
<div class="submit" >
<van-button :loading="loading" round block type="primary" @click="onSubmit">保存资料</van-button>
</div>
  </div>
</template>

<style lang="css" scoped>
.avatar {
  padding: 30px;
  text-align: center;
  background-color: var(--mk-white);
}

.avatar-img {
  box-shadow: 0 0 5px var(--mk-gray);
}

.avatar-btn {
  color: var(--mk-linear_end);
  margin-top: 10px;
}

.gender ::v-deep(.van-cell__title) {
  width: 100px;
  flex: none;
}

.van-radio-group {
  display: flex;
  justify-content: space-between;
  height: 36px;
  width: 180px;
}

.submit {
  padding: 16px;
}
</style>
